var express = require('express');
var router = express.Router();
const path = require('path');

const shortid = require('shortid');

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync');
const adapter = new FileSync(path.resolve(__dirname, '../data/db.json'));
// 获取db对象
const db = low(adapter);

// 记账本列表
router.get('/account', function (req, res, next) {
  // 获取所有的账单信息
  let accounts = db.get('accounts').value();

  res.render('list', { accounts });
});

// 添加记录
router.get('/account/create', function (req, res, next) {
  res.render('create')
});

// 新增记录
router.post('/account', function (req, res, next) {
  // 获取请求体数据
  // 生成id
  let id = shortid.generate();
  // 写入文件
  db.get('accounts').unshift({ id, ...req.body }).write();
  res.render('success', { msg: '添加成功', url: '/account' })
});

// 删除记录
router.get('/account/:id', (req, res) => {
  // 获取params的id参数
  let { id } = req.params;
  // 删除
  db.get('accounts').remove({ id }).write();
  // 提醒
  res.send('success', { msg: '删除成功', url: '/account' })
})

module.exports = router;
